import React, {useCallback, useEffect, useState} from "react";
import {Popconfirm, Button, Col, DatePicker, Icon, Modal, Row, Select, Table} from "antd";
import {deleteAlarm, getAlarmList, handleAlarm} from "../../api/alarm";
import moment from "moment";
import AlarmCompare from "../../components/AlarmCompare";


const {Option} = Select
const {RangePicker} = DatePicker

const pageSize = 10
const tableHead = {
	"index": "序号",
	"channel_name": "链路名称",
	"collector_name": "采集点名称",
	"alarm_log_type_display": "异常类型",
	"result_display": "处理结果",
	"occur_at": "异常开始时间",
	"end_at": "异常结束时间",
	"handle": "操作"
}


function MonitorResult({}) {
	const [columns, setColumns] = useState()
	const [currentAlarmType, setCurrentAlarmType] = useState(() => '')
	const [currentAlarm, setCurrentAlarm] = useState()
	const [currentPage, setCurrentPage] = useState(1)
	const [result, setResult] = useState('')
	const [alarmResult, setAlarmResult] = useState([])
	const [loading, setLoading] = useState(true)
	const [showModal, setShowModal] = useState(false)
	const [rangeDate, setRangeDate] = useState([formatTime(moment().subtract(1, 'month'), 'start'), formatTime(moment(), 'end')])

	function formatTime(time, type) {
		const momentRange = type === 'start' ? moment(time).startOf('day') : moment(time).endOf('day')
		const ISOTimeStr = momentRange.format()
		return ISOTimeStr
	}

	const onAlarmTypeChange = useCallback((value) => {
		setCurrentAlarmType(value)
	}, [])

	const onRangeChange = useCallback(value => {
		// console.log(value);
		// setRangeDate([value[0].toISOString(), value[1].toISOString()])
		setRangeDate([formatTime(value[0], 'start'), formatTime(value[1], 'end')])
	})

	const onResultChange = useCallback(value => {
		setResult(value)
	}, [result])
	const onEditClick = (record) => {
		return () => {
			setCurrentAlarm(record)
			setShowModal(true)
		}
	}

	const onDeleteClick = (record) => () => {
		// console.log(2222, result);
		deleteAlarm(record.id).then(res => {
			getAlarm()
		})
	}


	//获取警告数据
	const getAlarm = () => {
		setLoading(true)
		// console.log(1111, result)
		getAlarmList({
			page_size: pageSize,
			page: currentPage,
			alarm_log_type: currentAlarmType,
			start: rangeDate[0],
			end: rangeDate[1],
			order: '-occur_at',
			result //N(未处理)，H(处理中)，C(已处理)，P(误报)，默认为N
		}).then(res => {
			setAlarmResult(res)
		}).finally(() => {
			setLoading(false)
		})
	}

	useEffect(() => {
		// console.log('setColumns');
		const tempCol = []
		Object.keys(tableHead).map(key => {
			const column = {
				title: tableHead[key],
				dataIndex: key,
				key
			}
			switch (key) {
				case 'index':
					column.width = "140px"
					column.render = (text, record, index) => {
						return index + 1
					}
					break;
				case 'occur_at':
				case 'end_at':
					column.render = (text, record, index) => {
						return text == null ? '无' : moment(text).format("yyyy-MM-DD HH:mm:ss")
					}
					break;
				case 'handle':
					column.render = (text, record, index) => {
						return (
							<>
								<Icon type={'edit'} onClick={onEditClick(record)}/>
								<Popconfirm title={'确认删除该异常吗？'} onConfirm={onDeleteClick(record)}>
									<Icon type={'delete'} style={{marginLeft: "20px"}}/>
								</Popconfirm>
							</>
						)
					}
					break;
				default:
					break;
			}
			tempCol.push(column)
		})
		setColumns(tempCol)
	}, [result])
	useEffect(() => {
		getAlarm()
		// console.log(rangeDate)
	}, [currentPage, currentAlarmType, rangeDate, result])

	return (
		<>
			<Row type={'flex'}>
				<Col>
					类型:&nbsp;&nbsp;<Select defaultValue={''} onChange={onAlarmTypeChange} style={{width: '200px'}}>
					<Option value={''}>全部</Option>
					<Option value={'D'}>不匹配</Option>
					<Option value={'B'}>采集器信号中断</Option>
				</Select>
				</Col>
				<Col offset={1}>
					处理结果:&nbsp;&nbsp;
					<Select defaultValue={''} onChange={onResultChange} style={{width: '200px'}}>
						<Option value={''}>全部</Option>
						<Option value={'N'}>未处理</Option>
						{/*<Option value={'H'}>处理中</Option>*/}
						<Option value={'C'}>已处理</Option>
						<Option value={'S'}>系统处理</Option>
						{/*<Option value={'P'}>误报</Option>*/}
					</Select>
				</Col>
				<Col offset={1}>
					统计时间:&nbsp;&nbsp;
					<RangePicker defaultValue={[moment().subtract(1, "month"), moment()]}
					             onChange={onRangeChange}></RangePicker>
				</Col>
				{/*<Col offset={1}>
					<Button type={'primary'}>确定</Button>
				</Col>*/}
			</Row>
			<Table
				bordered rowKey={'id'}
				dataSource={alarmResult.results}
				columns={columns}
				style={{marginTop: '20px', background: '#fff'}}
				loading={loading}
				pagination={{
					pageSize: pageSize,
					total: alarmResult.count,
					onChange: (pageNum, pageSize) => {
						// console.log(page)
						// page = pageNum
						// this.initTable()
						setLoading(true)
						setCurrentPage(pageNum)
					}
				}}
			/>
			<Modal
				title={currentAlarm?.channel_name}
				visible={showModal}
				destroyOnClose
				width={'70%'}
				okText={currentAlarm?.result !== 'C' ? '处理' : '确定'}
				onCancel={() => {
					setShowModal(false)
				}}
				onOk={() => {
					if (currentAlarm?.result !== 'C') {
						handleAlarm({
							id: currentAlarm.id,
							sample_media_url: currentAlarm.sample_media_url,
							meta_media_url: currentAlarm.meta_media_url
						}).then(res => {
							getAlarm()
						})
					}
					setShowModal(false)
				}}
			>
				<AlarmCompare item={currentAlarm}/>
			</Modal>
		</>
	)
}

export default MonitorResult
